﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TRSADO.NET;
using System.Data.SqlClient;
using System.Threading;
using System.Collections.Generic;
using AjaxPro;
using Patent.DBUtility;

namespace Patent
{
    /// <summary>
    /// Topic 的摘要说明
    /// </summary>
    public class Topic
    {

        /// <summary>
        /// 国外专利TRS表名
        /// </summary>
        private string[] otherPatent ={"chpatent","depatent","frpatent","gbpatent","jppatent","uspatent","eppatent","wopatent" };

        /// <summary>
        /// 国内专利TRS表名
        /// </summary>
        private string[] chinesePatent ={ "fmzl","syxx","wgzl"};

        SQLHelper helper;
       
        public Topic()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //

            helper = new SQLHelper();
        }

        /// <summary>
        /// 获取专题列表
        /// </summary>
        /// <returns></returns>
        public DataSet Getlist()
        {
            string cmdText = "select * from ptcase_m";
            DataSet ds = new DataSet();
            helper.RunSQL(cmdText, ref ds);
            return ds;
        }

        /// <summary>
        /// 新建专题，获取专题ID
        /// </summary>
        /// <returns></returns>
        [AjaxMethod()]
        public int GetMaxID()
        {
            string cmdText = "select max(专题编号) from ptcase_m";
            SqlDataReader dataReader;
            int maxID=0;
            helper.RunSQL(cmdText, out dataReader);
            if (dataReader.Read())
            {
                maxID = dataReader.IsDBNull(0) ? 0 : dataReader.GetInt32(0);
            }
            dataReader.Close();
            return maxID;
            
        }


        /// <summary>
        /// 更新 数据导入 进度
        /// </summary>
        /// <param name="ztTable"></param>
        /// <param name="clientCount"></param>
        /// <param name="sumCount"></param>
        /// <param name="orTable"></param>
        public void UpdateProcess(string ztTable,int clientCount, int sumCount, string orTable, string tableList)
        {
            string sqlStr = "insert into ptprocess (专题信息表,当前位置,记录总数,数据表名,数据表列表) values ('"+ztTable+"',"+clientCount+","+sumCount+",'"+orTable+"','"+tableList+"')";
            helper.RunSQL(sqlStr);
        }


        /// <summary>
        /// 使用AJAX方法，获取当前数据导入进度
        /// </summary>
        /// <param name="ztTable">专题表名</param>
        /// <returns>进度字符串</returns>
        [AjaxMethod()]
        public  string GetProcessStr(string ztTable,string currentTable)
        {
            string processStr = "";
            string cmdText = "" +
                        " if exists(select 1 from ptprocess where 专题信息表='" + ztTable + "' and 数据表名='" + currentTable + "') " +
                        "    begin  " +
                        "        if exists(select 1 from ptprocess where 专题信息表='" + ztTable + "' and 数据表名='" + currentTable + "' and 当前位置!=记录总数) " +
                        "            begin " +
                        "                select top 1 ltrim(当前位置)+','+ltrim(记录总数)+','+数据表名 as 进度数据  from ptprocess where 专题信息表='" + ztTable + "' and 数据表名='" + currentTable + "' " +
                        "            end " +
                        "        else " +
                        "            begin " +
                        "                select 'done' as 进度数据 " +
                        "            end " +
                        "    end " +
                        " else " +
                        "    begin " +
                        "        select 'wait' as 进度数据 " +
                        "    end ";
            SqlDataReader reader;
            helper.RunSQL(cmdText, out reader);
            if (reader.Read())
            {
                processStr=reader.IsDBNull(0)?"done":reader.GetString(0);
            }
            reader.Close();
            //SystemError.CreateErrorLog(processStr);
            return processStr;
        }

        /// <summary>
        /// 根据查询逻辑表达式生成物理表达式数组
        /// </summary>
        /// <param name="queryValue">查询表达式</param>
        /// <param name="queryTable">查询数据表， 如果是多表， 用逗号连接</param>
        /// <returns></returns>
        public Dictionary<string, string> ConvertQueryString(string queryValue, string queryTables)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            foreach (string table in queryTables.Split(','))
            {
                dictionary.Add(table, this.getQueryString(queryValue, table)); 
            }
            return dictionary;
        }

        /// <summary>
        /// 建立专题
        /// </summary>
        /// <param name="topicName">专题名称</param>
        /// <param name="value">专题表达式</param>
        /// <returns></returns>
        [AjaxMethod()]
        public string CreateTopic(string topicName, string value)
        {
            string returnValue = "";
            int topicID = GetMaxID() + 1;
            string topicDate = DateTime.Now.ToShortDateString();
            string dataSource = value.Split('_')[1];
            string topicAuthor = "admin";
            SqlParameter[] para = new SqlParameter[6];
            para[0] = helper.CreateInParam("@topicID", SqlDbType.Int, 0, topicID);
            para[1] = helper.CreateInParam("@topicName",SqlDbType.VarChar,40,topicName);
            para[2] = helper.CreateInParam("@topicValue",SqlDbType.VarChar,4000,value);
            para[3] = helper.CreateInParam("@topicDate",SqlDbType.VarChar,10,topicDate);
            para[4] = helper.CreateInParam("@topicAuthor",SqlDbType.VarChar,10,topicAuthor);
            para[5] = helper.CreateInParam("@topicSource",SqlDbType.VarChar,11,initDataSourceString(dataSource));
            try
            {
                SqlDataReader reader;
                helper.RunProc("pro_CreateTopic", para, out reader);
                if (reader.Read())
                {
                    returnValue = reader.IsDBNull(0) ? "" : reader.GetString(0) + "," + reader.GetString(1);
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                SystemError.CreateErrorLog("topic  :"+ex.Message);
            }
            //SystemError.CreateErrorLog("crateTopic");
            return returnValue;
           
        }

        /// <summary>
        /// 进度(有问题：长度不能小于 0。参数名: length)
        /// </summary>
        /// <param name="topicStr">专题字符串, ect: 4,case3_ptinfo</param>
        /// <param name="value">专题表达式</param>
        /// <returns></returns>
        [AjaxMethod()]
        public bool ProcessQuery(string topicStr,string value)
        {
            try
            {
                // SystemError.CreateErrorLog(topicStr);
                string topicID = topicStr.Split(',')[0];
                if ("case" + topicID != topicStr.Split(',')[1].Split('_')[0])
                {
                    //  SystemError.CreateErrorLog("false");
                    return false;
                }
                string queryValue = value.Split('_')[0];
                string queryTables = value.Split('_')[1];


                Dictionary<string, string> dictionary = ConvertQueryString(queryValue, queryTables);
                foreach (KeyValuePair<string, string> kvp in dictionary)
                {

                    TRSSQL trs = new TRSSQL();
                    int sumRecords = trs.GetTotalCount(kvp.Key, kvp.Value);
                    SqlDataReader reader;
                    reader = trs.ExecuteReader(kvp.Key, kvp.Value);

                    UpdateProcess(topicStr.Split(',')[1], 0, sumRecords, kvp.Key, queryTables);
                    if (isChinesePatent(kvp.Key))
                    {
                        if (reader.Read())
                        {
                            do
                            {
                                SqlParameter[] para = new SqlParameter[27];
                                para[0] = helper.CreateInParam("@topicID", SqlDbType.Int, 0, topicID);

                                para[1] = helper.CreateInParam("@zlh", SqlDbType.VarChar, 14, reader["专利号"]);
                                para[2] = helper.CreateInParam("@gkr", SqlDbType.VarChar, 10, reader["公开日"]);
                                para[3] = helper.CreateInParam("@gkh", SqlDbType.VarChar, 14, reader["公开号"]);
                                para[4] = helper.CreateInParam("@sqh", SqlDbType.VarChar, 14, reader["申请号"]);
                                para[5] = helper.CreateInParam("@sqrq", SqlDbType.VarChar, 10, reader["申请日"]);
                                para[6] = helper.CreateInParam("@fmr", SqlDbType.VarChar, 1000, replaceStr(reader["发明人"].ToString()));
                                para[7] = helper.CreateInParam("@sqr", SqlDbType.VarChar, 200, replaceStr(reader["申请人"].ToString()));
                                para[8] = helper.CreateInParam("@zflh", SqlDbType.VarChar, 10, reader["主分类号"]);
                                para[9] = helper.CreateInParam("@flh", SqlDbType.VarChar, 100, reader["分类号"]);
                                para[10] = helper.CreateInParam("@mc", SqlDbType.VarChar, 300, replaceStr(reader["名称"].ToString()));
                                para[11] = helper.CreateInParam("@zy", SqlDbType.VarChar, 4000, "摘要"); //摘要
                                para[12] = helper.CreateInParam("@zqx", SqlDbType.VarChar, 4000, "主权项");//主权项
                                para[13] = helper.CreateInParam("@yxq", SqlDbType.VarChar, 200, reader["优先权"]);
                                para[14] = helper.CreateInParam("@yxqr", SqlDbType.VarChar, 10, "");  //优先权日
                                para[15] = helper.CreateInParam("@tzzlx", SqlDbType.VarChar, 100, ""); //同族专利项  
                                para[16] = helper.CreateInParam("@gsdm", SqlDbType.VarChar, 10, this.getGSDMFromGSDM(reader["国省代码"].ToString()));
                                //SystemError.CreateErrorLog(" GSDM:" + reader["国省代码"]);
                                para[17] = helper.CreateInParam("@pctgk", SqlDbType.VarChar, 20, "");  //PCT公开
                                para[18] = helper.CreateInParam("@pctxx", SqlDbType.VarChar, 4000, ""); //PCT信息
                                para[19] = helper.CreateInParam("@pctsq", SqlDbType.VarChar, 30, "");   //PCT申请
                                para[20] = helper.CreateInParam("@zbyzl", SqlDbType.VarChar, 100, ""); //再版原专利
                                para[21] = helper.CreateInParam("@dlr", SqlDbType.VarChar, 100, reader["代理人"]);
                                para[22] = helper.CreateInParam("@bzr", SqlDbType.VarChar, 10, reader["颁证日"]);
                                para[23] = helper.CreateInParam("@zldljg", SqlDbType.VarChar, 100, reader["专利代理机构"]);
                                para[24] = helper.CreateInParam("@dz", SqlDbType.VarChar, 300, reader["地址"]);
                                para[25] = helper.CreateInParam("@zllx", SqlDbType.VarChar, 10, GetPatentType(kvp.Key));
                                para[26] = helper.CreateInParam("@zlzz", SqlDbType.VarChar, 100, kvp.Key);

                                helper.RunProc("pro_ProcessData", para);
                            }
                            while (reader.Read());
                        }

                    }
                    else
                    {
                        while (reader.Read())
                        {

                            SqlParameter[] para = new SqlParameter[27];
                            para[0] = helper.CreateInParam("@topicID", SqlDbType.Int, 0, topicID);
                   
                            para[1] = helper.CreateInParam("@zlh", SqlDbType.VarChar, 14, reader["专利号"]);
                            para[2] = helper.CreateInParam("@gkr", SqlDbType.VarChar, 10, reader["公开日"]);
                            para[3] = helper.CreateInParam("@gkh", SqlDbType.VarChar, 14, reader["公开号"]);
                            para[4] = helper.CreateInParam("@sqh", SqlDbType.VarChar, 14, reader["申请号"]);
                            para[5] = helper.CreateInParam("@sqrq", SqlDbType.VarChar, 10, reader["申请日"]);
                            para[6] = helper.CreateInParam("@fmr", SqlDbType.VarChar, 1000, replaceStr(reader["发明人"].ToString()));
                            para[7] = helper.CreateInParam("@sqr", SqlDbType.VarChar, 200, replaceStr(reader["申请人"].ToString()));
                            para[8] = helper.CreateInParam("@zflh", SqlDbType.VarChar, 10, reader["主分类号"]);
                            para[9] = helper.CreateInParam("@flh", SqlDbType.VarChar, 100, reader["分类号"]);
                            para[10] = helper.CreateInParam("@mc", SqlDbType.VarChar, 300, replaceStr(reader["名称"].ToString()));
                            para[11] = helper.CreateInParam("@zy", SqlDbType.VarChar, 4000, "摘要"); //摘要 
                            para[12] = helper.CreateInParam("@zqx", SqlDbType.VarChar, 4000, "主权项"); //主权项
                            para[13] = helper.CreateInParam("@yxq", SqlDbType.VarChar, 200, reader["优先权"]);
                            para[14] = helper.CreateInParam("@yxqr", SqlDbType.VarChar, 10, "");   //优先权日
                            para[15] = helper.CreateInParam("@tzzlx", SqlDbType.VarChar, 200, ""); //同族专利项
                            para[16] = helper.CreateInParam("@gsdm", SqlDbType.VarChar, 10, this.getGSDMFromSQRAndFMR(reader["申请人"].ToString(),reader["发明人"].ToString()));
                           // SystemError.CreateErrorLog(" GSDM:" + this.getGSDMFromSQRAndFMR(reader["申请人"].ToString(), reader["发明人"].ToString()));
                            para[17] = helper.CreateInParam("@pctgk", SqlDbType.VarChar, 20, ""); //PCT公开
                            para[18] = helper.CreateInParam("@pctxx", SqlDbType.VarChar, 4000, ""); //PCT信息
                            para[19] = helper.CreateInParam("@pctsq", SqlDbType.VarChar, 30, ""); //PCT申请
                            para[20] = helper.CreateInParam("@zbyzl", SqlDbType.VarChar, 50, ""); //再版原专利
                            para[21] = helper.CreateInParam("@dlr", SqlDbType.VarChar, 100, replaceStr(reader["代理人"].ToString()));
                            para[22] = helper.CreateInParam("@bzr", SqlDbType.VarChar, 10, reader["颁证日"]);
                            para[23] = helper.CreateInParam("@zldljg", SqlDbType.VarChar, 100, replaceStr(reader["专利代理机构"].ToString()));
                            para[24] = helper.CreateInParam("@dz", SqlDbType.VarChar, 100, "");  //地址
                            para[25] = helper.CreateInParam("@zllx", SqlDbType.VarChar, 10, GetPatentType(kvp.Key));
                            para[26] = helper.CreateInParam("@zlzz", SqlDbType.VarChar, 100, kvp.Key);

                            helper.RunProc("pro_ProcessData", para);
                        }
                    }
                    reader.Close();
                }

            }
            catch (Exception ex)
            {
                SystemError.CreateErrorLog("topic:" + ex.Message);
                return false;
            }
            return true;
        }


        /// <summary>
        /// 国省代码处理
        /// </summary>
        /// <param name="gsdm"></param>
        /// <returns></returns>
        public string getGSDMFromGSDM(string gsdm)
        {
            string returnGSDM = "Others";
            string[] temps = gsdm.Split(';');
            if (temps.Length == 2)
            {
                returnGSDM = temps[1];
            }
            return returnGSDM;
        }

        /// <summary>
        /// 申请人，取出国省代码信息
        /// </summary>
        /// <param name="sqr">申请人</param>
        /// <returns></returns>
        public string getGSDMFromSQRAndFMR(string sqr,string fmr)
        {
            string returnGSDM = "Others";
            int starIndex = sqr.IndexOf('[');
            int endIndex = sqr.IndexOf(']');
            if (starIndex > 0)
            {
                returnGSDM = sqr.Substring(starIndex + 1, endIndex - starIndex - 1);
            }
            else
            {
                starIndex = sqr.IndexOf('(');
                endIndex = sqr.IndexOf(')');
                if (starIndex > 0)
                {
                    returnGSDM = sqr.Substring(starIndex + 1, endIndex - starIndex - 1);
                }
            }

            if (returnGSDM.Trim() == "" || returnGSDM == "Others")
            {
                starIndex = fmr.IndexOf('[');
                endIndex = fmr.IndexOf(']');
                if (starIndex > 0)
                {
                    returnGSDM = fmr.Substring(starIndex + 1, endIndex - starIndex - 1);
                }
                else
                {
                    starIndex = fmr.IndexOf('(');
                    endIndex = fmr.IndexOf(')');
                    if (starIndex > 0)
                    {
                        returnGSDM = fmr.Substring(starIndex + 1, endIndex - starIndex - 1);
                    }
                }
            }
            return returnGSDM;
        }

        /// <summary>
        /// 字符过滤
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string replaceStr(string str)
        {
            string returnValue = str;
            returnValue=returnValue.Replace("'","''");
            //returnValue = returnValue.Replace("(","");
           // returnValue = returnValue.Replace(")","");
           // returnValue = returnValue.Replace("!", "");
            returnValue = returnValue.Replace("%", "");
            return returnValue;
        }

        /// <summary>
        /// 通过TRS表名获取专利类型
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public string GetPatentType(string tableName)
        {
            if (tableName == "fmzl")
                return "发明";
            if (tableName == "wgzl")
                return "外观";
            if (tableName == "syxx")
                return "实用";
            return "发明";
        }

        /// <summary>
        /// 判断是否为中国专利数据
        /// </summary>
        /// <param name="tableName">TRS表名</param>
        /// <returns></returns>
        public bool isChinesePatent(string tableName)
        {
            bool returnValue = false;
            foreach (string str in chinesePatent)
            {
                if (str == tableName.Trim().ToLower())
                {
                    returnValue = true;
                    break;
                }
            }
            return returnValue;
        }

        /// <summary>
        /// 处理查询表达式
        /// </summary>
        /// <param name="queryValue">客户端生成的表达式</param>
        /// <param name="queryTable">客户端选择数据源</param>
        /// <returns></returns>
        public string getQueryString(string queryValue, string queryTable)
        {
            string returnString=queryValue;
            while (true)
            {
                if (isChinesePatent(queryTable)==false)
                {
                  //  returnString = returnString.Replace("#A","申请号");
                    returnString = returnString.Replace("#A","申请日");
                  //  returnString = returnString.Replace("#C","公开（公告）号");
                    returnString = returnString.Replace("#B", "公开日");
                  //  returnString = returnString.Replace("#E", "专利号");
                    returnString = returnString.Replace("#C", "授权日");
                  //  returnString = returnString.Replace("#G", "名称");

                    returnString = returnString.Replace("#D", "发明人");
                    returnString = returnString.Replace("#E", "申请人");
                    returnString = returnString.Replace("#F", "主分类号");
                    returnString = returnString.Replace("#G", "分类号");
                    returnString = returnString.Replace("#H", "地址");
                    returnString = returnString.Replace("#I", "权利项");
                    returnString = returnString.Replace("#J", "摘要");
                    returnString = returnString.Replace("#K", "优先权");
                    break;
                }
                else
                {
                 //   returnString = returnString.Replace("#A", "申请号");
                    returnString = returnString.Replace("#A", "申请日");
                  //  returnString = returnString.Replace("#C", "公开（公告）号");
                    returnString = returnString.Replace("#B", "公开日");
                  //  returnString = returnString.Replace("#E", "专利号");
                    returnString = returnString.Replace("#C", "授权日");
                  //  returnString = returnString.Replace("#G", "名称");

                    returnString = returnString.Replace("#D", "发明人");
                    returnString = returnString.Replace("#E", "申请人");
                    returnString = returnString.Replace("#F", "主分类号");
                    returnString = returnString.Replace("#G", "分类号");
                    returnString = returnString.Replace("#H", "地址");
                    returnString = returnString.Replace("#I", "权利项");
                    returnString = returnString.Replace("#J", "摘要");
                    returnString = returnString.Replace("#K", "优先权");
                    break;
                }
            }
            return returnString;
        }


        /// <summary>
        /// 生成一个11位的二进制字符串用于表达专题数据源
        /// </summary>
        /// <param name="dataSource"></param>
        /// <returns></returns>
        public string initDataSourceString(string dataSource)
        {
            string returnString = "";
            if (dataSource.Contains("uspatent"))
            {
                returnString += "1";
            }
            else
            {
                returnString += "0";
            }

            if (dataSource.Contains("jppatent"))
            {
                returnString += "1";
            }
            else
            {
                returnString += "0";
            }

            if (dataSource.Contains("gbpatent"))
            {
                returnString += "1";
            }
            else
            {
                returnString += "0";
            }

            if (dataSource.Contains("depatent"))
            {
                returnString += "1";
            }
            else
            {
                returnString += "0";
            }


            if (dataSource.Contains("frpatent"))
            {
                returnString += "1";
            }
            else
            {
                returnString += "0";
            }

            if (dataSource.Contains("chpatent"))
            {
                returnString += "1";
            }
            else
            {
                returnString += "0";
            }

            if (dataSource.Contains("wopatent"))
            {
                returnString += "1";
            }
            else
            {
                returnString += "0";
            }

            if (dataSource.Contains("eppatent"))
            {
                returnString += "1";
            }
            else
            {
                returnString += "0";
            }


            if (dataSource.Contains("fmzl"))
            {
                returnString += "1";
            }
            else
            {
                returnString += "0";
            }

            if (dataSource.Contains("syxx"))
            {
                returnString += "1";
            }
            else
            {
                returnString += "0";
            }

            if (dataSource.Contains("wgzl"))
            {
                returnString += "1";
            }
            else
            {
                returnString += "0";
            }
            return returnString;
        }
    }

}